<?php
    include_once("db_connect.php");

    if(!empty($_POST["access"])){
	$access = $_POST["access"];
	pg_exec("DELETE FROM public.caller_project_time");
	foreach ($access as $key_pr=>$acc_pr){
	    for($i=0; $i<=6; $i++){
		if(empty($acc_pr[$i][1]) || empty($acc_pr[$i][2])) { 
		    $acc_pr[$i][1] = "00:00"; 
		    $acc_pr[$i][2] = "00:00"; 
		}
		pg_exec("INSERT INTO public.caller_project_time (prt_id, pro_id, prt_dow, prt_time_begin, prt_time_end) 
			VALUES 
		        (nextval('caller_project_time_prt_id_seq'), $key_pr, $i, '".$acc_pr[$i][1]."', '".$acc_pr[$i][2]."')");
	    }
	}
	header("Location: /caller/access.php");
    }
?>
<?php
    include_once("menu.php");
?>
<h2>Access Time</h2>
<form method="post">

<?php
    $projects_sql = pg_exec('select * from public.caller_project');
    while($t = pg_fetch_array($projects_sql)){
	$projects[$t['pro_id']] = $t['pro_name'];
    }
    $access_sql = pg_exec('select * from public.caller_project_time');
    while($t = pg_fetch_array($access_sql)){
	$access[$t['pro_id']][$t['prt_dow']][1] = $t['prt_time_begin'];
	$access[$t['pro_id']][$t['prt_dow']][2] = $t['prt_time_end'];
    }
?>

<table border=1>

<?php

    echo "<tr><td></td>";
    for($i=1; $i<=6; $i++){
	echo "<td align=center>$i</td>";
    }
    echo "<td align=center>0</td>";
    echo "</tr>";
    
    foreach($projects as $key_pr=>$project){
	echo "<tr><td>$project</td>";
	for($i=1; $i<=6; $i++){
	    echo "<td><input value='";
	    echo (empty ($access[$key_pr][$i][1]))?'00:00':$access[$key_pr][$i][1];
	    echo "' size='5' maxlength='8' name='access[$key_pr][$i][1]'> - ";
	    echo "<input value='";
	    echo (empty ($access[$key_pr][$i][1]))?'00:00':$access[$key_pr][$i][2];
	    echo "' size='5' maxlength='8' name='access[$key_pr][$i][2]'></td>";
	}
	    echo "<td><input value='";
	    echo (empty ($access[$key_pr][0][1]))?'00:00':$access[$key_pr][0][1];
	    echo "' size='5' maxlength='8' name='access[$key_pr][0][1]'> - ";
	    echo "<input value='";
	    echo (empty ($access[$key_pr][0][1]))?'00:00':$access[$key_pr][0][2];
	    echo "' size='5' maxlength='8' name='access[$key_pr][0][2]'></td>";
	echo "</tr>";
    }
?>

</table>
<input type="submit" value="submit" name="submit"><br />
</form>

<?php    
    include_once("db_disconnect.php");
?>